package cn.sc.summer.calculate.manager;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.sc.summer.calculate.po.SysTask;
import cn.sc.summer.calculate.po.SysTaskLog;
import cn.sc.summer.calculate.service.TaskService;
import cn.sc.summer.calculate.service.impl.TaskServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import cn.sc.summer.constant.project.DateConstant;
import cn.sc.summer.constant.util.DateUtilX;
import cn.sc.summer.exception.util.ip.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 类名：定时任务执行监听器
 *
 * @author a-xin
 * @date 2024/2/6 16:32
 */
@Slf4j
@Component
public class CustomJobListener implements JobListener {

    @Override
    public String getName() {
        return "CustomJobListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        String jobName = context.getJobDetail().getKey().getName();
        log.info("==> The job: {} is about to be executed!", jobName);
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        String jobName = context.getJobDetail().getKey().getName();
        log.error("The job: {} was vetoed and not executed!", jobName);
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        saveSysTaskLog(context, jobException);
    }

    /**
     * 存储定时任务日志信息
     *
     * @param context      定时任务信息
     * @param jobException 执行异常
     */
    private void saveSysTaskLog(JobExecutionContext context, JobExecutionException jobException) {
        SysTaskLog sysTaskLog = new SysTaskLog();
        sysTaskLog.setId(IdWorker.getIdStr());

        String className = context.getJobDetail().getJobClass().getName();
        sysTaskLog.setBeanClass(className);

        TaskService taskService = SpringUtil.getBean(TaskServiceImpl.class);
        SysTask sysTaskInfo = taskService.getSysTaskInfoByBeanClass(className);
        sysTaskLog.setJobId(sysTaskInfo.getId());
        sysTaskLog.setJobName(sysTaskInfo.getJobName());
        sysTaskLog.setJobGroup(sysTaskInfo.getJobGroup());
        sysTaskLog.setCronExpression(sysTaskInfo.getCronExpression());
        sysTaskLog.setHandleIp(IPUtil.getNacosInstanceIp());

        sysTaskLog.setHandleStartTime(DateUtilX.format(new Date(), DateConstant.YYYY_MM_DD_HH_MM_SS_1));
        sysTaskLog.setHandleCode(200);

        if (ObjectUtil.isNotNull(jobException)) {
            sysTaskLog.setHandleMessage(jobException.getMessage());
            sysTaskLog.setHandleCode(500);
        }
        taskService.saveSysTaskLog(sysTaskLog);
    }

}

